/** 接口调用工具*/
import axios from 'axios'  //引用axios
import {Toast} from 'vant';
import api from './api';
// 配置API接口地址
axios.interceptors.request.use(
    config => {
        config.headers['Content-Type']="application/json;charset=UTF-8";
        const toast = Toast.loading({
            // mask: true,
            forbidClick:true,
            message: '加载中...'
          });
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// 自定义判断元素类型JS
function toType(obj) {
    return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}

/** 参数过滤函数*/
function filterNull(o) {
    for (var key in o) {
        if (o[key] === null) {
            delete o[key]
        }
        if (toType(o[key]) === 'string') {
            o[key] = o[key].trim()
        } else if (toType(o[key]) === 'object') {
            o[key] = filterNull(o[key])
        } else if (toType(o[key]) === 'array') {
            o[key] = filterNull(o[key])
        }
    }
    return o
}

/**添加headers,可以动态添加header参数*/
function setHeaders() {
    axios.defaults.headers.Authorization = "78283bbdd2984ac841ff6bebdcd89be0";//localStorage.getItem("token");
}


//其实success与failure这两个参数，传过来的是两个放方法
function apiAxios(method, url, params, success) {
    setHeaders()
    if (params) {
        params = filterNull(params)
    }
    axios({
        method: method,
        url: url,
        data: method === 'POST' || method === 'PUT' ? params : null,
        params: method === 'GET' || method === 'DELETE' ? params : null,
        baseURL: api.root,
        withCredentials: false
    })
        .then(function (res) {
            setTimeout(() => {
                Toast.clear();
            }, 1000);
            if (res.headers.authorization) {
                localStorage.setItem("token", res.headers.authorization) //token
            }
            success(res.data)
        }).catch(function (err) {
            setTimeout(() => {
                Toast.clear();
            }, 1000);
            let res = err.response
            if(res){
                success(res.data)
            }
    })
}
//导出
export default {
    get: function (url, params, success) {
        return apiAxios('GET', url, params, success)
    },
    post: function (url, params, success) {
        return apiAxios('POST', url, params, success)
    }
}